import type { FormInstance } from 'element-plus'
import type { SystemDeptOptionsType, SystemDeptPostDataItemType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElButton,
  ElIcon,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElMessage
} from 'element-plus'
import { CirclePlus, CircleClose } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'SystemDeptPostOptions',
  props: ['visible', 'type', 'record', 'rowId'],
  emits: ['cancel'],
  setup(props: SystemDeptOptionsType, { emit }) {
    const store = useStore()

    const ruleFormRef = ref<FormInstance>()
    const deptPostListRef = ref()
    const deptPostValidateForm = reactive<SystemDeptPostDataItemType>({})
    const title = { add: '新增', update: '编辑', read: '查看', addSon: '新增子项' }

    Object.assign(deptPostValidateForm, props.record)
    for (const i in deptPostListRef.value) {
      if (deptPostListRef.value[i].id === deptPostValidateForm?.postId) {
        deptPostValidateForm.postName = deptPostListRef.value[i].postName
        deptPostValidateForm.postId = ''
        break
      }
    }

    onMounted(() => {
      getSelectByTenant()
    })

    // 岗位
    const getSelectByTenant = async () => {
      const res = await store.dispatch('systemDept/GetSelectByTenant') // 岗位
      if (res?.code === 200) {
        deptPostListRef.value = res.data
      }
    }

    // 新增->提交
    const handleSubmitForm = (formEl: FormInstance | undefined) => {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validate(async (valid) => {
        if (!valid) return
        const params = {
          ...deptPostValidateForm,
          deptId: props.rowId
        }
        const res = await store.dispatch('systemDept/PostDeptPostSubmit', params)
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          handleCloseModal() // 关闭新增
          if (!formEl) return
          formEl.resetFields()
        } else {
          ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
        }
      })
    }

    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    return () => {
      const { type, visible } = props
      return (
        <ElDialog
          title={(title[type!] as string) || '查看'}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={() => handleCloseModal()}
          v-slots={
            type !== 'read' && {
              footer: () => (
                <>
                  <ElButton type="primary" onClick={() => handleSubmitForm(ruleFormRef.value)}>
                    <ElIcon>
                      <CirclePlus />
                    </ElIcon>
                    &nbsp; {type === 'update' ? '修改' : '保存'}
                  </ElButton>
                  <ElButton onClick={() => handleCloseModal()}>
                    <ElIcon>
                      <CircleClose />
                    </ElIcon>
                    取消
                  </ElButton>
                </>
              )
            }
          }
        >
          <ElForm label-width="100px" ref={ruleFormRef} model={deptPostValidateForm}>
            <ElFormItem
              key="postId"
              prop="postId"
              label="岗位："
              rules={[{ required: true, message: '请选择 岗位', trigger: 'change' }]}
            >
              {type === 'read' ? (
                deptPostValidateForm.postName
              ) : (
                <ElSelect v-model={deptPostValidateForm.postId} placeholder="请选择 岗位" clearable>
                  {deptPostListRef.value?.map((item: { id: string; postName: string }) => (
                    <ElOption key={item?.id} label={item?.postName} value={item?.id}></ElOption>
                  ))}
                </ElSelect>
              )}
            </ElFormItem>
          </ElForm>
        </ElDialog>
      )
    }
  }
})
